<?php

namespace app\controller;

use support\Request;
use support\Response;
use app\model\RoomSettlement;
use app\model\RoomSettlementUser;
use app\model\User;

class TimelineController
{
    /**
     * 获取用户时间轴记录
     */
    public function getUserTimeline(Request $request): Response
    {
        $userId = $request->get('user_id');
        $page = (int)$request->get('page', 1);
        $pageSize = (int)$request->get('page_size', 20);
        
        if (!$userId) {
            return json(['success' => false, 'message' => '用户ID不能为空']);
        }

        try {
            error_log("获取用户时间轴: user_id={$userId}, page={$page}, page_size={$pageSize}");
            
            // 获取用户参与的所有已结算房间
            $roomUsers = \app\model\RoomUser::where('user_id', $userId)
                ->whereHas('room', function($query) {
                    $query->where('status', 'finished');
                })
                ->with(['room'])
                ->orderBy('joined_at', 'desc')
                ->paginate($pageSize, ['*'], 'page', $page);
                
            error_log("找到已结算房间数量: " . $roomUsers->count());

            $timeline = [];
            foreach ($roomUsers as $roomUser) {
                $room = $roomUser->room;
                
                // 获取结算记录
                $settlement = \app\model\RoomSettlement::where('room_id', $room->id)->first();
                
                // 获取用户在结算详情中的记录
                $settlementDetail = null;
                if ($settlement) {
                    $settlementDetail = \app\model\RoomSettlementDetail::where('settlement_id', $settlement->id)
                        ->where('user_id', $userId)
                        ->first();
                }
                
                $timeline[] = [
                    'id' => $settlement ? $settlement->id : $room->id,
                    'room_id' => $room->id,
                    'room_code' => $room->room_code,
                    'room_name' => $room->name,
                    'settlement_time' => $settlement ? $settlement->settlement_time->format('Y-m-d H:i:s') : $room->updated_at->format('Y-m-d H:i:s'),
                    'settlement_type' => $settlement ? $settlement->settlement_type : 'unknown',
                    'settlement_reason' => $settlement ? $settlement->settlement_reason : '房间已结束',
                    'total_players' => $settlement ? $settlement->total_players : 0,
                    'total_transactions' => $settlement ? $settlement->total_transactions : 0,
                    'user_final_score' => $settlementDetail ? $settlementDetail->final_score : $roomUser->current_score,
                    'is_winner' => $settlementDetail ? $settlementDetail->is_winner : ($roomUser->current_score > 0),
                    'is_room_owner' => $settlementDetail ? $settlementDetail->is_room_owner : ($room->created_by == $userId),
                    'joined_at' => $roomUser->joined_at ? $roomUser->joined_at->format('Y-m-d H:i:s') : null,
                    'left_at' => $roomUser->left_at ? $roomUser->left_at->format('Y-m-d H:i:s') : null,
                    'user_settlement_strategy' => $settlementDetail ? $settlementDetail->settlement_strategy : null,
                ];
            }

            return json([
                'success' => true,
                'data' => [
                    'timeline' => $timeline,
                'pagination' => [
                    'current_page' => $roomUsers->currentPage(),
                    'total_pages' => $roomUsers->lastPage(),
                    'total_items' => $roomUsers->total(),
                    'per_page' => $roomUsers->perPage(),
                    'has_more' => $roomUsers->hasMorePages()
                ]
                ]
            ]);

        } catch (\Exception $e) {
            error_log('获取用户时间轴失败: ' . $e->getMessage());
            return json(['success' => false, 'message' => '获取时间轴记录失败']);
        }
    }

    /**
     * 获取用户统计信息
     */
    public function getUserStats(Request $request): Response
    {
        $userId = $request->get('user_id');
        
        if (!$userId) {
            return json(['success' => false, 'message' => '用户ID不能为空']);
        }

        try {
            // 获取用户统计信息
            $stats = \app\model\RoomSettlementDetail::getUserStats($userId);
            
            // 获取最近10场游戏记录
            $recentDetails = \app\model\RoomSettlementDetail::where('user_id', $userId)
                ->with(['settlement'])
                ->orderBy('created_at', 'desc')
                ->take(10)
                ->get();
                
            $recentGames = $recentDetails->map(function($detail) {
                return [
                    'room_code' => $detail->settlement->room_code,
                    'room_name' => $detail->settlement->room_name,
                    'final_score' => $detail->final_score,
                    'is_winner' => $detail->is_winner,
                    'settlement_time' => $detail->settlement->settlement_time->format('Y-m-d H:i:s'),
                ];
            });

            return json([
                'success' => true,
                'data' => [
                    'total_games' => $stats['total_games'],
                    'total_wins' => $stats['total_wins'],
                    'total_losses' => $stats['total_losses'],
                    'win_rate' => $stats['win_rate'],
                    'total_score' => $stats['total_score'],
                    'max_score' => $stats['max_score'],
                    'min_score' => $stats['min_score'],
                    'recent_games' => $recentGames
                ]
            ]);

        } catch (\Exception $e) {
            error_log('获取用户统计信息失败: ' . $e->getMessage());
            return json(['success' => false, 'message' => '获取统计信息失败']);
        }
    }

    /**
     * 获取房间结算详情
     */
    public function getRoomSettlementDetail(Request $request): Response
    {
        $settlementId = $request->get('settlement_id');
        
        if (!$settlementId) {
            return json(['success' => false, 'message' => '结算ID不能为空']);
        }

        try {
            $settlement = RoomSettlement::with(['creator'])
                ->find($settlementId);
                
            if (!$settlement) {
                return json(['success' => false, 'message' => '结算记录不存在']);
            }

            $settlementData = [
                'id' => $settlement->id,
                'room_id' => $settlement->room_id,
                'room_code' => $settlement->room_code,
                'room_name' => $settlement->room_name,
                'settlement_type' => $settlement->settlement_type,
                'settlement_reason' => $settlement->settlement_reason,
                'settlement_time' => $settlement->settlement_time->format('Y-m-d H:i:s'),
                'total_players' => $settlement->total_players,
                'total_transactions' => $settlement->total_transactions,
                'total_score' => $settlement->total_score,
                'creator' => [
                    'id' => $settlement->creator->id,
                    'username' => $settlement->creator->username
                ],
                'players' => \app\model\RoomSettlementDetail::getRoomSettlementDetails($settlementId),
                'settlement_strategy' => $settlement->settlement_strategy ?? null,
                'transfers' => \app\model\AccountingRecord::where('room_id', $settlement->room_id)
                    ->where('type', 'score')
                    ->with(['user', 'targetUser'])
                    ->get()
                    ->map(function($record) {
                        return [
                            'from_user_id' => $record->user_id,
                            'from_username' => $record->user->username ?? '未知用户',
                            'to_user_id' => $record->target_user_id,
                            'to_username' => $record->targetUser->username ?? '未知用户',
                            'amount' => $record->score,
                            'description' => $record->description,
                            'created_at' => $record->created_at->format('Y-m-d H:i:s')
                        ];
                    })
            ];

            return json([
                'success' => true,
                'data' => $settlementData
            ]);

        } catch (\Exception $e) {
            error_log('获取房间结算详情失败: ' . $e->getMessage());
            return json(['success' => false, 'message' => '获取结算详情失败']);
        }
    }
}
